package com.baoxin.chenxixc4coach.java;

import com.baoxin.chenxixc4coach.MyApplication;
import com.baoxin.chenxixc4coach.utils.Interfaces;
import com.baoxin.chenxixc4coach.utils.NetUtil;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 验证Token是否过期
 */
public class TokenInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);
        if (isTokenExpired(response)) {
            String newToken = getNewToken();
            if (newToken.length() != 0) {
                Request newRequset = chain.request()
                        .newBuilder()
                        .header("token", newToken)
                        .build();
                return chain.proceed(newRequset);
            }else {
                //重新登录
            }
        }
        return response;
    }

    private boolean isTokenExpired(Response response) {
        if (response.code() == 8888888) {
            return true;
        }
        return false;
    }

    private String getNewToken() {
        String newToken = "";
        String userName = MyApplication.getUserName();
        String password = MyApplication.getPassword();
        try {
            newToken = NetUtil.getNewToken(Interfaces.URL_LOGIN_IN, userName, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return newToken;
    }
}
